//
//  YHistoryViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/1/5.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YHistoryViewController.h"
#import "YHistoryTableViewCell.h"
#import "VVPickerDate.h"
#import "HiModel.h"
#import "YEventViewController.h"
#import "YHistoryInfoViewController.h"

@interface YHistoryViewController ()<UITableViewDelegate,UITableViewDataSource,VVPickerDateDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *textF;
@property (weak, nonatomic) IBOutlet UIButton *searchButton;
- (IBAction)searchButtonAction:(UIButton *)sender;

@property (weak, nonatomic) IBOutlet UIButton *sTimeB;
@property (weak, nonatomic) IBOutlet UIButton *fTimeB;
@property(nonatomic,strong)NSString *strTime;
@property(nonatomic,strong)NSString *endTime;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
- (IBAction)sTimeBAction:(UIButton *)sender;
- (IBAction)fTimeBAction:(UIButton *)sender;
@property(nonatomic,strong)NSString *timeButton;
@property(nonatomic,strong)NSMutableArray *eventAr;
@end

@implementation YHistoryViewController
-(NSMutableArray *)eventAr{
    if (!_eventAr) {
        self.eventAr = [NSMutableArray new];
    }
    return _eventAr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"历史记录";
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    [self.tableView registerNib:[UINib nibWithNibName:@"YHistoryTableViewCell" bundle:nil] forCellReuseIdentifier:@"historyCell"];
    
    //按钮加边框
    
    [self.sTimeB.layer setBorderWidth:1];//设置边界的宽度
    [self.fTimeB.layer setBorderWidth:1];
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    
    CGColorRef color = CGColorCreate(colorSpaceRef, (CGFloat[]){225/255.0,227/255.0,229/255.0,1});
    [self.sTimeB.layer setBorderColor:color];
    [self.fTimeB.layer setBorderColor:color];
    
    
    //设置默认时间
    
    self.textF.delegate = self;
    
    [self timeNew];
    
}

-(void)timeNew{
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    
    [formatter setDateFormat:@"YYYY-MM-dd"];
    NSString *DateTime = [formatter stringFromDate:date];
    NSLog(@"%@============年-月-日=====================",DateTime);
    
    [self.fTimeB setTitle:DateTime forState:UIControlStateNormal];
    
    self.strTime = @"2017-02-27";
    self.endTime = DateTime;
    
    [self loadDataFormUrl];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.eventAr.count;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YHistoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"historyCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    HiModel *model = self.eventAr[indexPath.row];
//    cell.imageV.image = [UIImage imageNamed:model.imageName];
    cell.name.text = model.Sitename;
    cell.event.text = [NSString stringWithFormat:@"%@",model.event];
    cell.danger.text = [NSString stringWithFormat:@"%@",model.danger];
//    cell.time.text = model.time;
    
    
//    if ([model.event integerValue] > 0) {
//        [cell.event setTextColor:[UIColor redColor]];
//            }else{
//        [cell.event setTextColor:[UIColor colorWithRed:31/255.0 green:33/255.0 blue:36/255.0 alpha:1]];
//    }
//    if ([model.danger integerValue] > 0) {
//        [cell.danger setTextColor:[UIColor redColor]];
//
//    }else{
//        [cell.danger setTextColor:[UIColor colorWithRed:31/255.0 green:33/255.0 blue:36/255.0 alpha:1]];
//    }
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    YHistoryInfoViewController *historyInfoV = [YHistoryInfoViewController new];
    HiModel *model = self.eventAr[indexPath.row];
    historyInfoV.webId = model.ID;
    historyInfoV.starTime = self.strTime;
    historyInfoV.endTime = self.endTime;
    
    self.hidesBottomBarWhenPushed = YES;
    [self showViewController:historyInfoV sender:nil];
}
#pragma mark - --- delegate 视图委托 ---





/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSDate *)dateFromString:(NSString *)dateString {
    if (!dateString) {
        return nil;
    }
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: @"yyyy-MM-dd"];
    [formatter setLocale:[NSLocale currentLocale]];
    NSDate *date= [formatter dateFromString:dateString];
    return date;
}
- (IBAction)sTimeBAction:(UIButton *)sender {
    [self datePicker];
    self.timeButton = @"sta";
}

- (IBAction)fTimeBAction:(UIButton *)sender {
    [self datePicker];
    self.timeButton = @"ftim";
}

-(void)datePicker{
    VVPickerDate *datePicker = [[VVPickerDate alloc]initWithDelegate:self date:[self dateFromString:self.endTime] beginDate:[self dateFromString:@"2017-02-27"]];
    [datePicker show];
    datePicker.delegate = self;
}
-(void)pickerDate:(STPickerDate *)pickerDate year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day{
    NSString *staStr = [NSString stringWithFormat:@"%ld",(long)year];
    
    NSString *staStrMo = [staStr stringByAppendingString:[NSString stringWithFormat:@"-%ld",(long)month]];
    
    NSString *staStrDay = [staStrMo stringByAppendingString:[NSString stringWithFormat:@"-%ld",(long)day]];
    if ([self.timeButton isEqualToString:@"sta"]) {
        self.strTime  = staStrDay;
        [self.sTimeB setTitle:staStrDay forState:UIControlStateNormal];
    }else{
        self.endTime = staStrDay;
        [self.fTimeB setTitle:staStrDay forState:UIControlStateNormal];
        self.eventAr = nil;
        
    }
    [self loadDataFormUrl];
    
}


//请求数据
-(void)loadDataFormUrl{
    
    
    NSDictionary *parameter = @{@"contactid":[[NSUserDefaults standardUserDefaults] stringForKey:@"userid"],@"startime":self.strTime,@"endtime":self.endTime,@"Sitename":self.textF.text};
    
    //    NSLog(@"%@",dict);
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    // post请求
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexAppHistory/history_list" parameters:parameter constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"11111111111111%@", dic);
        NSArray *dataAr = dic[@"list"];
        
        for (NSDictionary *dic in dataAr) {
            NSLog(@"2222222222%@",self.eventAr);
            
            HiModel *model = [HiModel new];
            [model setValuesForKeysWithDictionary:dic];
            
            
            [self.eventAr insertObject:model atIndex:0];
        }
//        //        冒泡排序
//        for(int i = 0;i < [self.arrayModel count]-1;i++){
//            for(int j = i+1;j<[self.arrayModel count];j++){
//                homeModel *modeli = self.arrayModel[i];
//                homeModel *modelj = self.arrayModel[j];
//                int numi= [modeli.event intValue] +[modeli.danger intValue];
//                int numj= [modelj.event intValue] +[modelj.danger intValue];
//                
//                if(numi<numj) {
//                    //交换
//                    [self.arrayModel exchangeObjectAtIndex:i withObjectAtIndex:j];
//                    
//                }
//            }
//        }
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        // 请求失败
        // [self alertWithString:@"请稍后再试"];
    }];
    
    
    //[self loginUrl];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.textF resignFirstResponder];

}

- (IBAction)searchButtonAction:(UIButton *)sender {
    [self.textF resignFirstResponder];
    self.eventAr = nil;
    [self loadDataFormUrl];
}
@end
